<template>
  <el-card body-style="min-height: 86vh">
    <!-- 搜索 -->
    <el-form :model="searchForm">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="车牌号" label-width="80">
            <el-input v-model="searchForm.licensePlate" placeholder="请输入车牌号" style="width: 340px"
              size="large"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车牌颜色" label-width="80">
            <el-select v-model="searchForm.carColor" placeholder="请选择车牌颜色" style="width: 340px" size="large">
              <el-option v-for="dict in colorTypeList" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车辆类别" label-width="80">
            <el-select v-model="searchForm.carCategory" placeholder="请选择车辆类别" style="width: 340px" size="large">
              <el-option v-for="dict in carCategoryList" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="车籍地" label-width="80">
            <el-select v-model="searchForm.carRegistration" placeholder="请选择车籍地" style="width: 340px" size="large">
              <el-option v-for="dict in areaList" :key="dict.areaCode" :label="dict.area" :value="dict.areaCode" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="归属企业" label-width="80">
            <el-input v-model="searchForm.belongCompany" placeholder="请输入归属企业" style="width: 340px"
              size="large"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审核状态" label-width="80">
            <el-select v-model="searchForm.verificationStatus" placeholder="请选择审核状态" style="width: 340px" size="large">
              <el-option v-for="dict in verificationStatusList" :key="dict.value" :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检测站" label-width="80">
            <el-select v-model="searchForm.testStation" placeholder="请选择检测站" style="width: 340px" size="large">
              <el-option v-for="dict in checkStationList" :key="(dict as any).id" :label="(dict as any).shortName"
                :value="(dict as any).id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="推送状态" label-width="80">
            <el-select v-model="searchForm.pushStatus" placeholder="请选择推送状态" style="width: 340px" size="large">
              <el-option v-for="dict in pushStatusList" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="受理时间" label-width="80">
            <el-date-picker v-model="searchForm.timeRange" type="daterange" size="large" range-separator="至"
              start-placeholder="开始时间" end-placeholder="结束时间" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button size="large" @click="handleRestSearch()">重置</el-button>
            <el-button type="primary" size="large" @click="handleGetTableList()">搜索</el-button>
            <!-- 导出后面再写 -->
            <!-- <el-button type="success" size="large" @click="handleGetTableList()">导出</el-button> -->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-divider />
    <!-- 新增、筛选按钮 -->
    <div class="flex justify-between">
      <div>
        <el-button type="primary" @click="handleCreate">新增年审记录</el-button>
      </div>
      <!-- 刷新按钮 -->
      <div class="flex justify-between">
        <div></div>
        <div>
          <el-text class="text-2xl" size="large" text="ture" disabled>配额数：<span type="primary" size="large">{{ annualNum }}</span></el-text>

          <el-button circle @click="handleGetTableList()">
            <template #icon><el-icon>
                <Refresh />
              </el-icon></template>
          </el-button>
        </div>
      </div>
    </div>
    <el-table :data="tableData" max-height="600" style="width:100%"  border>
      <el-table-column label="序号" type="index" min-width="50" align="center"/>
      <el-table-column prop="acceptanceId" label="受理编号" min-width="80" align="center" show-overflow-tooltip />
      <el-table-column prop="licensePlate" label="车牌号码" min-width="100" align="center" show-overflow-tooltip />
      <el-table-column prop="carColor" label="车牌颜色" min-width="60" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span>{{colorTypeList.find((item) => item.value === scope.row.carColor)?.label}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="carCategory" label="车辆类别" min-width="80" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span>{{
            carCategoryList.find((item) => item.value === scope.row.carCategory)?.label
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="carType" label="车辆类型" min-width="100" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span>{{
            carCategoryList
              .find((item) => item.value === scope.row.carCategory)
              ?.options.find((item) => item.value === scope.row.carType)?.label
          }}</span>
        </template>
      </el-table-column>
     
      <el-table-column prop="operatorPhone" label="经办人电话" min-width="100" align="center" show-overflow-tooltip/>
      <el-table-column prop="testStation" label="检测站" width="100" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ getCheckStationLabel(scope.row.testStation) }}</span>
        </template>
      </el-table-column>
      <el-table-column  label="检测站电话" min-width="100" align="center" show-overflow-tooltip>1770880332</el-table-column>

      <el-table-column prop="belongCompany" label="所属企业" min-width="100" align="center" show-overflow-tooltip/>

      <el-table-column prop="carRegistration" label="车籍地" min-width="90" align="center" show-overflow-tooltip >
        <template #default="scope">
          <span>{{
            areaList.find((item) => item.areaCode == scope.row.carRegistration)?.area
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="acceptanceTime" label="受理时间" min-width="100" align="center" show-overflow-tooltip/>
      <el-table-column prop="validityTime" label="有效期至" min-width="100" align="center" show-overflow-tooltip/>
      <el-table-column prop="archivingStatus" label="归档" min-width="80" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.archivingStatus == 0" size="small" type="info">未归档</el-tag>
          <el-tag v-if="scope.row.archivingStatus == 1" size="small" type="primary">已归档</el-tag>
        </template>
      </el-table-column>
      <!-- 推送状态：0未推送，1：已推送，2推送失败 -->
      <el-table-column prop="pushStatus" label="推送" min-width="80" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.pushStatus == 0" size="small" type="info" >未推送</el-tag>
          <el-tag v-if="scope.row.pushStatus == 1" size="small" type="primary" >已推送</el-tag>
          <el-tag v-if="scope.row.pushStatus == 2" size="small" type="danger">推送失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="pushInformation" label="推送情况" min-width="120" align="center" />

      <!-- 审核状态、：0未审核，1审核中，2通过，3，未通过，4复审，取消作废 -->
      <el-table-column prop="verificationStatus" label="审核状态" min-width="80" align="center" fixed="right">
        <template #default="scope">
          <el-tag v-if="scope.row.verificationStatus == 0" size="small">未审核</el-tag>
          <el-tag v-if="scope.row.verificationStatus == 1" type="warning" size="small">审核中</el-tag>
          <el-tag v-if="scope.row.verificationStatus == 2" type="success" size="small">通过</el-tag>
          <el-tag v-if="scope.row.verificationStatus == 3" type="danger" size="small">未通过</el-tag>
          <el-tag v-if="scope.row.verificationStatus == 4" type="primary" size="small">复审</el-tag>
          <el-tag v-if="scope.row.verificationStatus == 5" type="info" size="small">作废</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" min-width="280" align="center" fixed="right">
        <!-- row是 -->
        <template #default="{ row }">
          <!-- 审核员 -->
          <!--  v-if="userStore.userInfo.identity == 344" -->
          <div v-if="(userStore.userInfo as any).identity == 344">
            <el-button type="primary" class="mx-0" @click="handleViewCheckCar(row)">审核</el-button>
            <el-button type="primary" class="mx-0" v-show="row.verificationStatus != 0"
              @click="handleScheduleRecord(row)">进度</el-button>
          </div>
          <div v-else>
            <el-button type="primary" class="mx-0" v-show="row.preResult == 0 || row.verificationStatus == 0"
              @click="handlePreliminaryRecord(row)">预审</el-button>
            <el-button type="primary" v-show="row.verificationStatus == 3" class="mx-0"
              @click="handleReviewRecord(row)">复审</el-button>
            <el-button type="primary" class="mx-0" v-show="row.verificationStatus != 0"
              @click="handleScheduleRecord(row)">进度</el-button>
            <el-button type="primary" class="mx-0" @click="handleViewRecord(row)">查看</el-button>
            <el-button type="primary" class="mx-0" v-show="row.preResult == 0" @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" class="mx-0" v-show="row.verificationStatus == 2">推送</el-button>
            <!--推送， 归档预审全部通过才可以推送，归档 -->
            <el-button type="primary" class="mx-0" v-show="row.verificationStatus == 2">归档</el-button>
            <el-button type="primary" class="mx-0" v-show="row.preResult == 0"
              @click="handleEditRecord(row)">修改</el-button>
            <el-popconfirm title="确定要将该条记录作废?" width="220" @confirm="handleCancellation(row)">
              <template #reference>
                <el-button type="danger" class="mx-0" v-show="row.verificationStatus !== 2">作废</el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="flex justify-center mt-2" background layout="total,prev, pager, next"
      :current-page="currentPage" :page-size="limit" :total="total" @current-change="handleGetTableList" />

    <form-drawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit()" confirmText="确认并前往预审">
      <el-form ref="formRef" :model="form" :rules="xrules" label-width="80px">
        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="form.licensePlate" placeholder="请输入车牌号"></el-input>
        </el-form-item>
        <el-form-item label="车牌颜色" prop="carColor">
          <el-select v-model="form.carColor" placeholder="请选择车牌颜色">
            <el-option v-for="dict in colorTypeList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="车籍地" prop="carRegistration">
          <el-select v-model="form.carRegistration" placeholder="请选择车籍地">
            <el-option v-for="dict in areaList" :key="dict.areaCode" :label="dict.area" :value="dict.areaCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆类别" prop="carCategory">
          <el-select v-model="form.carCategory" placeholder="请选择车辆类别">
            <el-option v-for="dict in carCategoryList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆类型" prop="carType">
          <el-select v-model="form.carType" placeholder="请选择车辆类型">
            <el-option v-for="dict in carCategoryList.find((item) => item.value === form.carCategory)
              ?.options" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属企业" prop="belongCompany">
          <el-input v-model="form.belongCompany" placeholder="请选择所属企业"></el-input>
        </el-form-item>
        <el-form-item label="上牌日期" prop="registrationTime">
          <el-date-picker v-model="form.registrationTime" type="date" placeholder="请选择上牌日期"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
      </el-form>
    </form-drawer>

    <!-- 预检 -->
    <preliminary-record ref="preliminaryRecordRef" @refresh="handleGetTableList" :recorditem="preliminaryRecordItem" />
    <!-- 查看 -->
    <view-record ref="viewRecordRef" />
    <!-- 进度 -->
    <schedule-record ref="scheduleRecordRef" />
    <!-- 复审 -->
    <review-record ref="reviewRecordRef" />
    <!-- 修改信息 -->
    <AddAnnualCar ref="addAnnualCarRef"></AddAnnualCar>
    <!-- 审核材料 -->
    <ViewCheckCar ref="viewCheckCarRef" @refresh="handleGetTableList"></ViewCheckCar>
  </el-card>
</template>
<script setup lang="ts">
import { defineAsyncComponent, ref } from "vue";
import { useInitForm, useInitTable } from "@/hooks/useCommon";
import { getAreaListApi } from "@/api/user";
import { getCheckStationListApi } from "@/api/second";
import {
  getAllAnnualReviewRecord,
  updateAnnualReviewRecordApi,
  addAnnualReviewRecordApi,
  recordUpdateCancel,
  getAnnualAuditFeeDetails
} from "@/api/annualAudit";
import {
  colorTypeList,
  carCategoryList,
  verificationStatusList,
  pushStatusList
} from "@/enum/index";
import { ElMessage } from "element-plus";
// 得到pinia中的user数据
import useUserStore from "@/stores/modules/user";
import { isCarNum } from "@/utils/regular";
const userStore = useUserStore();
console.log(userStore.userInfo);

const PreliminaryRecord = defineAsyncComponent(() => import("./components/preliminaryRecord.vue"));
const ViewRecord = defineAsyncComponent(() => import("./components/viewRecord.vue"));
const ScheduleRecord = defineAsyncComponent(() => import("./components/scheduleRecord.vue"));
const ReviewRecord = defineAsyncComponent(() => import("./components/reviewRecord.vue"));
const AddAnnualCar = defineAsyncComponent(() => import("./components/addAnnualCar.vue"));
const ViewCheckCar = defineAsyncComponent(() => import("./components/viewCheckCar.vue"));

const addAnnualCarRef = ref();
const handleEditRecord = (val: any) => {
  addAnnualCarRef.value.handleEdit(val);
};

const checkStationList = ref([]);
type areaListType = { areaCode: string; area: string }[];
const areaList = ref<areaListType>([]);

const { tableData, searchForm, currentPage, limit, total, handleRestSearch, handleGetTableList } =
  useInitTable({
    searchForm: {
      licensePlate: "",
      carColor: "",
      carCategory: "",
      carRegistration: "",
      belongCompany: "",
      verificationStatus: "",
      testStation: "",
      pushStatus: "",
      acceptanceTime: ""
    },
    getTableList: getAllAnnualReviewRecord
  });

const xrules = {
  licensePlate: [{ required: true, message: "车牌号不能为空", trigger: "blur" },
  {
    validator(rule: any, value: any, callback: any) {
      if (!isCarNum(value)) {
        callback(new Error("请输入正确的车牌号"));
      } else {
        callback();
      }
    }
  }
  ],
  carColor: [{ required: true, message: "车牌颜色不能为空", trigger: "blur" }],
  carRegistration: [{ required: true, message: "车籍地不能为空", trigger: "blur" }],
  carCategory: [{ required: true, message: "车辆类别不能为空", trigger: "blur" }],
  carType: [{ required: true, message: "车辆类型不能为空", trigger: "blur" }],
  belongCompany: [{ required: true, message: "所属企业不能为空", trigger: "blur" }]
};
//显示剩余配额数目
const annualNum = ref(0);
getAnnualAuditFeeDetails().then((res) => {
  annualNum.value = (res as any).annualNum;
});
// 新增编辑
const { formDrawerRef, drawerTitle, form, formRef, handleCreate, handleEdit, handleSubmit } =
  useInitForm({
    form: {
      carColor: "",
      licensePlate: "",
      carRegistration: "",
      carCategory: "",
      carType: "",
      belongCompany: "",
      registrationTime: ""
    },
    rules: {
      licensePlate: [{ required: true, message: "车牌号不能为空222", trigger: "blur" },
      {
        validator(rule: any, value: any, callback: any) {
          if (!isCarNum(value)) {
            callback(new Error("请输入正确的车牌号"));
          } else {
            callback();
          }
        }
      }
      ],
      carColor: [{ required: true, message: "车牌颜色不能为空", trigger: "blur" }],
      carRegistration: [{ required: true, message: "车籍地不能为空", trigger: "blur" }],
      carCategory: [{ required: true, message: "车辆类别不能为空", trigger: "blur" }],
      carType: [{ required: true, message: "车辆类型不能为空", trigger: "blur" }],
      belongCompany: [{ required: true, message: "所属企业不能为空", trigger: "blur" }]
    },
    createData: addAnnualReviewRecordApi,
    updateData: updateAnnualReviewRecordApi,
    success: (res: number) => {
      handlePreliminaryRecord({ id: res })
      handleGetTableList(currentPage.value);
    }
  });
//表格
handleGetTableList();
// 预览
const preliminaryRecordRef = ref();
const preliminaryRecordItem = ref();
const handlePreliminaryRecord = (val: any) => {
  console.log(val);
  preliminaryRecordRef.value.handleEdit(val);
};

// 查看
const viewRecordRef = ref();
const handleViewRecord = (val: any) => {
  viewRecordRef.value.handleOpen(val);
};
//审核材料
const viewCheckCarRef = ref();
const handleViewCheckCar = (val: any) => {
  console.log(viewCheckCarRef.value);
  viewCheckCarRef.value.handleOpen(val);
};

// 进度
const scheduleRecordRef = ref();
const handleScheduleRecord = (val: any) => {
  // scheduleRecordRef 是进度弹框组件
  // 下面的代码是调用 进度弹框组件的handleOpen方法，并传递参数val(即点击的那一行数据)
  scheduleRecordRef.value.handleOpen(val);
};
// 复审
const reviewRecordRef = ref();

const handleReviewRecord = (val: any) => {
  console.log(val);
  reviewRecordRef.value.handleOpen(val);
};

/** 获取检测站转换 */
const getCheckStationLabel = (testStation: any) => {
  for (let i = 0; i < checkStationList.value.length; i++) {
    if ((checkStationList.value[i] as any).id == testStation) {
      return (checkStationList.value[i] as any).shortName;
    }
  }
};

/** 获取检测站列表 */
const getCheckStationList = () => {
  getCheckStationListApi({}).then((response: any) => {
    checkStationList.value = response;
  });
};

/** 获取区县列表 */
const getAreaList = () => {
  getAreaListApi().then((response: any) => {
    areaList.value = response;
  });
};

// 作废
const handleCancellation = (row: any) => {
  console.log(row);
  // 发送请求进行作废
  recordUpdateCancel(row.id).then((res: any) => {
    if (res == true) {
      ElMessage.success("作废成功");
      handleGetTableList();
    }
  });
};

getCheckStationList();
getAreaList();
</script>
<style scoped lang="scss">
:deep(.el-button) {
  margin: 0 10px 10px 0;
}
.text-2xl{
  font-size: 18px;
  margin-right: 50px;

}
.text-2xl span {
  font-size: 24px;
  color: #409eff;
  font-weight: bold;
}
// ::v-deep .el-table__header th {
//   background-color: #409EFF !important; /* 表头背景色 */
//   color: white !important; /* 文字颜色 */
// }
</style>
